import './assets/main.scss'

import { createApp } from 'vue'
import pinia from './stores'
import router from './router'
import { type RouteLocationNormalized } from 'vue-router'
// import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css' // 不引入 ElMessageBox不显示
// import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { useUserStore } from './stores'
import App from './App.vue'
import { ElMessage } from 'element-plus'
// import api from '@/apis/api'

const app = createApp(App)
// 全局挂载api请求
// app.config.globalProperties.$api = api
app.use(pinia)

const userStore = useUserStore()

userStore.addMenu(router, 'refresh')

// 路由守卫拦截 全局前置守卫
function isRoute(to: RouteLocationNormalized) {
  return router.getRoutes().filter((item) => item.path === to.path).length > 0
}
router.beforeEach((to) => {
  // 这里不写 next参数可以不执行next()方法，直接返回路由对象
  if (to.path !== '/login' && !userStore.token) {
    return { name: 'login' }
  }
  if (!isRoute(to)) {
    ElMessage.error('没有找到此页面')
    return { name: '404' }
    // history.back() // 回到原来的页面
    // router.go(-1)
  }
})

app.use(router)
// mock服务拦截挂载
import '@/apis/mock'
// app.use(ElementPlus, {
//   locale: zhCn,
// })

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.mount('#app')
